package com.project.order;




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisZSetCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
@Component
public class OrderService {

    @Autowired
    private RedisTemplate redisTemplate;

    Calendar cal = Calendar.getInstance();

    Long nowTime=null;

    public static final String  ORDER_SET="OrderZSet";


    public void pushOrder(int orderId,Long overTime){

        if (Objects.isNull(redisTemplate)){

            System.out.println("无连接！");
        }

        redisTemplate.opsForZSet().add(ORDER_SET,orderId,overTime);

    }


    public int pullOrder()  {

        while (true) {

            Set<ZSetOperations.TypedTuple> orderSet = redisTemplate.opsForZSet().rangeWithScores(ORDER_SET, 0, 1);

            if (orderSet == null || orderSet.isEmpty()) {

                System.out.println("当前没有等待的任务");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                continue;


            }


            System.out.println("我他妈来啦！");

            Iterator<ZSetOperations.TypedTuple> iterator = orderSet.iterator();

            nowTime=System.currentTimeMillis();
            System.out.println(nowTime);

            while (iterator.hasNext()) {
                ZSetOperations.TypedTuple next = iterator.next();

                System.out.println(next.getScore().longValue());
                if (nowTime-(Long) next.getScore().longValue()>0){

                    redisTemplate.opsForZSet().removeRangeByScore(ORDER_SET,next.getScore(),next.getScore()+500);
                    System.out.println("我删除了！");
                }


            }






        }


    }


}
